package org.ccay.core.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import org.apache.log4j.Logger;
/**
 * 使用反射机制  没有get set方法 也可以获取对应的value
 * Created：2013-3-30
 * @author chaowangbang
 * @version:
 */
public  class ReflectUtil {
	private static Logger log = Logger.getLogger(ReflectUtil.class);

	private ReflectUtil() {

	}
	/**
	 * 指定当前属性 是否是public的
	 * @param field
	 * Created：2013-3-30
	 * @author chaowangbang
	 */
	private static void makeAccessible(Field field) {
		if (!Modifier.isPublic(field.getModifiers())) {
			field.setAccessible(true);
		}
	}
	/**
	 * 获取对象的公共属性
	 * @param object
	 * @param filedName
	 * @return
	 * Created：2013-3-30
	 * @author chaowangbang
	 */
	private static Field getDeclaredField(Object object, String filedName) {
		for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
				.getSuperclass()) {
			try {
				return superClass.getDeclaredField(filedName);
			} catch (NoSuchFieldException e) {
				// Field 不在当前类定义, 继续向上转型
				log.info("reflect error:" + filedName);
			}
		}
		return null;
	}
	/**
	 * 给对象指定的属性赋值
	 * @param object
	 * @param fieldName
	 * @param value
	 * Created：2013-3-30
	 * @author chaowangbang
	 */
	@Deprecated
	public static void setFieldValue(Object object, String fieldName,
			Object value) {
		Field field = getDeclaredField(object, fieldName);

		if (field == null){
			throw new IllegalArgumentException("Could not find field ["
					+ fieldName + "] on target [" + object + "]");
		}

		makeAccessible(field);

		try {
			field.set(object, value);
		} catch (IllegalAccessException e) {
			log.error("reflect error:" , e);
		}
	}
	/**
	 * 获取对象的 指定属性value
	 * @param object
	 * @param fieldName
	 * @return
	 * Created：2013-3-30
	 * @author chaowangbang
	 */
	@Deprecated
	public static Object getFieldValue(Object object, String fieldName) {
		Field field = getDeclaredField(object, fieldName);
		if (field == null){
			throw new IllegalArgumentException("Could not find field ["
					+ fieldName + "] on target [" + object + "]");
		}

		makeAccessible(field);

		Object result = null;
		try {
			result = field.get(object);
		} catch (IllegalAccessException e) {
			log.error("reflect error:", e);
		}
		return result;
	}

}